package com.haixee.parkdemo.data_acl.process;

import com.haixee.parkdemo.common.context.WebContextHolder;
import com.haixee.parkdemo.common.exception.BusinessException;
import com.haixee.parkdemo.common.response.CommonResEnum;
import com.haixee.parkdemo.common.response.ConPreProcessor;
import com.haixee.parkdemo.data_acl.annotation.DataAclSetting;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DataAccessPreProcessor implements ConPreProcessor {

    @SneakyThrows
    @Override
    public void process(ProceedingJoinPoint proceedingJoinPoint) {

        List<String> fieldList = WebContextHolder.getAuth().getFieldList();
        if (fieldList.size() == 0) {
            return;
        }

        Object[] args = proceedingJoinPoint.getArgs();
        if (args.length == 0) {
            return;
        }

        Object arg = args[0];
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();

        Method method = methodSignature.getMethod();
        DataAclSetting classNameAnnotation = method.getAnnotation(DataAclSetting.class);
        if (classNameAnnotation == null) {
            return;
        }

        Class<?> classData = classNameAnnotation.voClass();

        Map<String, Field> fieldMap = new HashMap<>();

        for (String fieldName : fieldList) {
            Field declaredField = classData.getDeclaredField(fieldName);
            declaredField.setAccessible(true);
            fieldMap.put(fieldName, declaredField);
        }


        for (Map.Entry<String, Field> fieldEntry : fieldMap.entrySet()) {
            Object o = fieldEntry.getValue().get(arg);
            if (o != null) {
                throw new BusinessException(CommonResEnum.PERMISSION_DENIED);
            }
        }



//        for (Field field : classData.getDeclaredFields()) {
//            Configurable annotation = field.getAnnotation(Configurable.class);
//            if (annotation != null) {
//                configurableNameMap.put(field.getName(), annotation.value());
//            }
//        }
//
//        if (configurableNameMap.size() == 0) {
//            return;
//        }

//        Map<String, List<FieldRule>> fieldRules = authRPCService.getFieldRules(aclId, configurableNameMap.keySet());
//        dealData((List<?>) result.getData(), fieldRules, classData);
//        addConfigureData(result, configurableNameMap, fieldRules);
    }

}
